
//////////////////////// LOADING A PAGE ////////////
function loadPage(sourceDiv, actionURL) {
        
    $.ajax ({       
        url:        actionURL + "?set_ajax_view",
        dataType:   "html",
        beforeSend: function() { 
            $('div#pageContent').hide("slow");
            $('div#' + sourceDiv).hide("slow");         
        },
        complete:   function() {
            $('div#' + sourceDiv).show("fast");         
        },
        success:  function(data) {
            $("#" + sourceDiv).html(data);          
        }
    });
}

/**
 * List all medicine coefficient of some department and medicine type. 
 */
function listMedicineCoef() {
	$.get(
			'../MedicineManagement/searchMedicineCoef?set_ajax_view',
			{
			deptId: $('select#departmentSearchLbx option:selected').val(),
			medTypeId: $('select#medicineTypeSearchLbx option:selected').val()
			},
			function(data) {
				$('table#medicineCoefTbl tbody').html('');
				if (data == '') {
					$('table#medicineCoefTbl tbody').append(_("Result not found."));
				} else {
					$('table#medicineCoefTbl tbody').append(data);
				}
			}
		);
}

/**
 * Get list of medicine names for one medicine type.
 */
function getMedicineNames(isSearch) {
	$.get(
			'../MedicineManagement/getMedicineNameByTypeAjax?set_ajax_view',
			{
			medTypeId: $('select#medicineTypeLbx option:selected').val()
			},
			function(data) {
				if (isSearch) {
					$('select#medicineNameLbx').html("<option id='all' value='all'>" + _("All") + "</option>");
				} else {
					$('select#medicineNameLbx').html("<option id='empty' value='empty'>" + _("Select medicine name") + "</option>");
				}
				$('select#medicineNameLbx').append(data);
			}
		);
}

function getQuantityTitle() {
	$.get(
			'../MedicineManagement/getQuantityTitleOfMedicine?set_ajax_view',
			{
			medicineId: $('select#medicineNameLbx option:selected').val()
			},
			function(data) {
				$('span#quantityTitle').html('');
				$('span#quantityTitle').append(data);
			}
		);
}

/**
 * Save medicine coefficient. 
 */
function saveMedicineCoef() {
	if (validateMedCoef()) {
		var submitData = $('#addMedicineCoefForm').formSerialize();
	    $.ajax ({
	            type:   "POST",
	            url:    "../MedicineManagement/saveMedicineCoefAjax?set_ajax_view",
	            data:   submitData,
	            beforeSend: function() {
	                $('#btn_save').hide();
	                $('#barLoading').show();                
	            },
	            complete:   function() {
	                $('#btn_save').show();
	                $('#barLoading').hide();
	            },
	            success:    function(data) {
	                if (data == '-1') {
						$('#statusMessage').html(_("Medicine coefficient existed") + "</font>");
					} else {
						// create mode, still remain the current page
						if ($('#medCoefId').val() == '') {
							$('#statusMessage').html("<font color='blue'>" + _("Medicine coefficient created") + "</font>");
							// refresh form
							$('select#medicineNameLbx').find("option[index='0']").attr("selected","selected");
							$('#quantityNumTxt').val('');
						} else {
					    // edit mode, close popup and refresh search page
					        $('div#editMedCoefDialog').dialog('close');
					        listMedicineCoef();
						}
					}
	            }
	    });
	}
}

/**
 * Validate medicine coefficient before saving.
 */
function validateMedCoef() {
	if ($('select#departmentLbx option:selected').val() == 'empty') {
		$('#statusMessage').html(_("Please select department"));
		return false;
	}
	if ($('select#medicineNameLbx option:selected').val() == 'empty') {
		$('#statusMessage').html(_("Please select medicine name"));
		return false;
	}
	var quantityNum = $('#quantityNumTxt').val();
	if ($.trim(quantityNum) == '') {
		$('#statusMessage').html(_("Please input quantity number"));
		return false;
	}
	if ($.trim(quantityNum).length > 0 && !isInteger(quantityNum)) {
		$('#statusMessage').html(_("Invalid quantity number"));
		return false;
	}
	return true;
}
 
/**
 * Open dialog to edit a medicine coefficient.
 * @param medCoefId The id of medicine coefficient
 */
function editMedCoef(medCoefId) {
	$.get(
			'../MedicineManagement/editMedicineCoef?set_ajax_view',
			{
		    medCoefId: medCoefId
			},
			function(data) {
				$('div#editMedCoefDialog').html(data);								
				generalDialog('editMedCoefDialog',null,null,null,{
					autoOpen: true,			
					bgiframe: true,
					resizable: true,		
					width: 500,
					height: 300,
					modal: true
				});			
			}
	);
}

/**
 * Save medicine coefficient quickly (only quantity number is changed).
 */
function saveMedCoefQuick(medCoefId) {
	var quantityNum = $('#medCoef_' + medCoefId + '_quantity_num').val();
	if ($.trim(quantityNum).length > 0 && !isInteger(quantityNum)) {
		generalDialog(null,null,_("Invalid quantity number"),'warn');
		return;
	} else {
		$.ajax ({
            type:   "GET",
            url:    "../MedicineManagement/saveMedicineCoefQuickly?set_ajax_view",
            data:   "medCoefId=" + medCoefId + "&quantityNum=" + quantityNum,
            beforeSend: function() {
                $('#medCoef_' + medCoefId + '_save').hide();
                $('#medCoef_' + medCoefId + '_barLoading').show();
            },
            complete:   function() {
                $('#medCoef_' + medCoefId + '_save').show();
                $('#medCoef_' + medCoefId + '_barLoading').hide();
            }            
		});
	}
}

/**
 * Remove a medicine coefficient. 
 * @param medCoefId The id of medicine coefficient
 */
function removeMedCoef(medCoefId) {
	$.get(
			'../MedicineManagement/removeOrUndoMedicineCoef?set_ajax_view',
			{
			medCoefId: medCoefId,
			activity: 'remove'
			},
			function(data) {
				$('#medCoef_' + medCoefId + '_remove').html('');
				$('#medCoef_' + medCoefId + '_remove').append(
						'<a href="javascript:undoMedCoef(' + medCoefId + ')" title="' + _("Reuse") + '">'
					+    	'<img src="../images/unlock_small.png" alt="' + _("Reuse") + '"></img>'  
		            + 	'</a>');
			}
		);
}

/**
 * Undo a medicine coefficient.
 * @param medCoefId The id of medicine coefficient
 */
function undoMedCoef(medCoefId) {
	$.get(
			'../MedicineManagement/removeOrUndoMedicineCoef?set_ajax_view',
			{
			medCoefId: medCoefId,
			activity: 'undo'
			},
			function(data) {
				$('#medCoef_' + medCoefId + '_remove').html('');
				$('#medCoef_' + medCoefId + '_remove').append(
						'<a href="javascript:removeMedCoef(' + medCoefId + ')" title="' + _("Delete") + '">'
					+    	'<img src="../images/lock_small.png" alt="' + _("Delete") + '"></img>'  
		            + 	'</a>');
			}
		);
}

/**
 * List medicine usage status for current department.
 */
function listMedicineUsgStatus() {
	$.get(
			'../MedicineManagement/searchMedicineUsgStatus?set_ajax_view',
			{
			medicineTypeId: $('select#medicineTypeLbx option:selected').val(),
			medicineId: $('select#medicineNameLbx option:selected').val(),
			},
			function(data) {				
				$('table#medicineUsgStatusTbl tbody').html('');
				if (data == '') {
					$('table#medicineUsgStatusTbl tbody').append(_("Result not found."));
				} else {
					$('table#medicineUsgStatusTbl tbody').append(data);
				}
			}
		);
}

/**
 * Update medicine usage status.
 */
function updateMedUsageStatus(medCoefId, medUsgStatusId) {	
	$.get(
			'../MedicineManagement/updateMedUsageStatus?set_ajax_view',
			{
		    medCoefId     : medCoefId,
			medUsgStatusId: medUsgStatusId
			},
			function(data) {
				$('div#updateMedUsgStatusDialog').html(data);
				generalDialog('updateMedUsgStatusDialog',null,null,null,{
					autoOpen: true,			
					bgiframe: true,
					resizable: true,		
					width: 600,
					height: 300,
					modal: true
				});			
			}
	);
}

/**
 * Create or update medicine usage status. 
 */
function saveMedicineUsgStatus() {
	if (validateMedUsgStatus()) {
		var submitData = $('#updateMedicineUsgStatusForm').formSerialize();
	    $.ajax ({
	            type:   "POST",
	            url:    "../MedicineManagement/saveMedUsageStatusAjax?set_ajax_view",
	            data:   submitData,
	            beforeSend: function() {
	                $('#btn_save').hide();
	                $('#barLoading').show();                
	            },
	            complete:   function() {
	                $('#btn_save').show();
	                $('#barLoading').hide();
	            },
	            success:    function(data) {
				    // close popup and refresh search page
					$('div#updateMedUsgStatusDialog').dialog('close');
					listMedicineUsgStatus();
	            }
	    });
	}
}

/**
 * Validate medicine usage status before saving.
 */
function validateMedUsgStatus() {
	var issueNum = $('#issueNumberTxt').val();
	var usedNum = $('#usedNumberTxt').val();
	var remainNum = $('#remainNumberTxt').val();
	
	if ($.trim(issueNum).length > 0 && !isInteger(issueNum)) {
		$('#statusMessage').html(_("Invalid issue number"));
		return false;
	}
	if ($.trim(usedNum).length > 0 && !isInteger(usedNum)) {
		$('#statusMessage').html(_("Invalid used number"));
		return false;
	}
	if ($.trim(remainNum).length > 0 && !isInteger(remainNum)) {
		$('#statusMessage').html(_("Invalid remain number"));
		return false;
	}
	return true;
}

/**
 * Update remain number when issue number or used number is changed.
 * Issue: (new) remain number = (old) remain number + (new issue number - old issue number)
 * Used: (new) remain number = (old) remain number - (new used number - old used number)
 * @param type
 * @return
 */
var oldIssueNumGlb;
var oldUsedNumGlb;
function updateRemainNumber(type) {
	var curRemainNum = +$('#remainNumberTxt').val();
	
	var newRemainNum = 0;
	if (type == 'issue') {
		var newIssueNum = +$('#issueNumberTxt').val();
		newRemainNum = curRemainNum + (newIssueNum - oldIssueNumGlb);
		oldIssueNumGlb = newIssueNum; 
	} else if (type == 'used') {
		var newUsedNum = +$('#usedNumberTxt').val();
		newRemainNum = curRemainNum - (newUsedNum - oldUsedNumGlb);
		oldUsedNumGlb = newUsedNum;
	}	
	$('#remainNumberTxt').val(newRemainNum);
}
